define(["angularAMD"], function (angularAMD) {
    angularAMD.service('CUS001Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$datePicker', '$mdDialog', '$calculater', '$mddProvider',
        function ($rootScope, $filter, $translate, config, $MMWService, $datePicker, $mdDialog, $calculater, $mddProvider) {

            this.init = function (machineItem, areaItem, plotItem, feedback) {

                var nowdatetime = $filter('date')(new Date(), 'yyyy/MM/dd HH:mm:ss');

                var openDialog = function (qcLists, checklist_no, checklist_display, qcDetails, machineItem, areaItem, plotItem) {
                    $mddProvider.UseForm('CUS001', () => {
                        $mdDialog.dialog(
                            'module/moduleCustomer/program/B02/CUS001/CUS001.html',
                            function (dialog) {
                                return {
                                    _title: $filter('translate')('CUS001.title'),
                                    css_url: 'module/moduleCustomer/program/B02/CUS001/CUS001.css',
                                    machineItem: machineItem,
                                    areaItem: areaItem, 
                                    plotItem: plotItem,
                                    // 产品编号 + 生产批号
                                    productno: plotItem.productno,
                                    plotNo: plotItem.plot_no,
                                    // 检验人
                                    handle_user_no: config.cache.account,
                                    handle_user_no_display: config.cache.name + "(" + config.cache.account + ")",
                                    // 检验时间
                                    handle_time: [nowdatetime.split(' ')[0], nowdatetime.split(' ')[1]],
                                    // 点检表信息
                                    qcLists: qcLists,
                                    // 已选点检表
                                    checklist_no: checklist_no,
                                    checklist_display: checklist_display,
                                    // 已选点检表明细
                                    machineCheckList: qcDetails,
                                    machineCheckList_display: qcDetails,
                                    // 是否使用
                                    do_flag: true,
                                    _event: {
                                        'handle_user_no': {
                                            click: () => {
                                                dialog.loadHandleUserNoList();
                                            }
                                        },
                                    },
                                    _fn: {
                                        'Execute': {
                                            click: () => {
                                                dialog.confirm();
                                            }
                                        }
                                    },

                                    // 检验人选择
                                    loadHandleUserNoList: function () {
                                        $MMWService.showQueryListPNIG({
                                            form_name: "PageNo_119",
                                            pageRecord: 50,
                                            condition: [
                                                { name: $filter('translate')('common.queryList.employee_c'), column_name: 'UserNo', query_mode: '2', value: dialog.handle_user_no }
                                            ],
                                            header: [
                                                { label: $filter('translate')('common.queryList.employee_c'), code: 'user_no' },
                                                { label: $filter('translate')('common.queryList.employee_n'), code: 'user_name' }
                                            ],
                                            setCondition: function (conditions) {
                                                conditions.push(
                                                    { column_name: 'IssueState', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                                                );
                                                return conditions;
                                            },
                                            selectCode: dialog.handle_user_no || '',
                                            confirm: function (selectItem, dialog2) {
                                                dialog.handle_user_no = selectItem.user_no;
                                                dialog.handle_user_no_display = selectItem.user_name + "(" + selectItem.user_no + ")";
                                                dialog2.hide();
                                            }
                                        });
                                    },

                                    // 检验时间选择
                                    changeDate: function () {
                                        $datePicker.open(dialog.handle_time[0],
                                            function (dialog2) {
                                                dialog.handle_time[0] = $filter('date')(dialog2.datePacker.pickDate, 'yyyy/MM/dd');
                                                dialog2.hide();
                                            },
                                            function (dialog2) {
                                                dialog2.hide();
                                            }, {});
                                    },
                                    changeTime: function () {
                                        var time = dialog.handle_time[1];
                                        var rule = /^\d{2}:\d{2}:\d{2}$/;
                                        if (rule.test(time) == false)
                                            time = "00:00:00";

                                        $calculater.open(
                                            function (timeDisplay, dialog2) {
                                                var hour = timeDisplay.hour, min = timeDisplay.minute, sec = timeDisplay.second;
                                                var time_str = hour + ":" + min + ":" + sec;
                                                if ((0 <= (+hour) && (+hour) < 24) &&
                                                    (0 <= (+min) && (+min) < 60) &&
                                                    (0 <= (+sec) && (+sec) < 60) && rule.test(time_str)) {
                                                    dialog.handle_time[1] = time_str;
                                                    dialog2.hide();
                                                } else {
                                                    $rootScope.showAlert($filter('translate')('common.msg.time_format_error'));
                                                }
                                            },
                                            function (dialog) {
                                                dialog.hide();
                                            },
                                            {
                                                type: "date",
                                                defaultNum: time,
                                                title: $filter('translate')('common.msg.select_time'),
                                                decimal: false
                                            });
                                    },

                                    // 点检表选择
                                    getCheckListNo: function () {
                                        var list = [];
                                        dialog.qcLists.forEach(function (item) { list.push({ "qclistno": item.qclistno, "qclistname": item.qclistname, }); });
                                        list = [...new Set(list.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));

                                        $rootScope.showQueryList({
                                            title: $filter('translate')('common.msg.plz_select'),
                                            header: [
                                                { label: $filter('translate')('B0210.qcListNo'), code: 'qclistno' },
                                                { label: $filter('translate')('B0210.qcListName'), code: 'qclistname' },
                                            ],
                                            query: function (conditions, feedback) {
                                                feedback(list);
                                            },
                                            confirm: function (selectItem, Dialog) {
                                                dialog.checklist_no = selectItem.qclistno;
                                                dialog.checklist_display = selectItem.qclistname + "(" + selectItem.qclistno + ")";

                                                $MMWService.sendToServer({
                                                    uri: 'ServicesCUS.Module_CUS.CUS_Product_QCList_Get_Process',
                                                    content: {
                                                        qclistno: selectItem.qclistno,
                                                        productno: dialog.productno
                                                    },
                                                    success: function (data) {
                                                        dialog.machineCheckList = data.qcDetails;
                                                        dialog.machineCheckList_display = data.qcDetails;
                                                        dialog.machineCheckList_display.forEach(function (item) {
                                                            item.do_flag = true
                                                        });
                                                    }
                                                });

                                                Dialog.hide();
                                            }
                                        })
                                    },

                                    // 是否使用选择
                                    ClickDoFlag: function () {
                                        dialog.do_flag = !dialog.do_flag;
                                        dialog.machineCheckList_display.forEach(function (item) {
                                            item.do_flag = dialog.do_flag
                                        });
                                    },
                                    ClickItemDoFlag: function (item) {
                                        item.do_flag = !item.do_flag;
                                    },

                                    // 点检值修改
                                    calculater: function (item, enableNegative) {
                                        var target = event.currentTarget;
                                        item.calculaterInput = true;
                                        angular.element(target).addClass('is-focus');
                                        $calculater.open(function (num, dialogType) {
                                            item.check_value = num;
                                            angular.element(target).removeClass('is-focus');
                                            item.calculaterInput = false;
                                            dialogType.hide();
                                        },
                                            function (dialogType) {
                                                angular.element(target).removeClass('is-focus');
                                                item.calculaterInput = false;
                                                dialogType.hide();
                                            },
                                            {
                                                defaultNum: item.check_value,
                                                decimal: true,
                                                enableNegative: enableNegative
                                            });
                                    },
                                    itemStatus: function (item) {
                                        if (!item) {
                                            return '';
                                        } else {
                                            if (item.check_type == '1') {
                                                if (item.std_value == item.check_value) {
                                                    item.check_result = '0'; //ok 0
                                                    return 'check-point-ok';
                                                } else {
                                                    item.check_result = '1'; //ng 1
                                                    return 'check-point-notok';
                                                }
                                            } else if (item.check_type == '2') {
                                                var isInterval = true;
                                                //M#85636 修正點檢項目區間為 0 以上時 沒輸入值 卻是合格狀態
                                                if (item.check_value == '' || item.check_value == null)
                                                    isInterval = false;
                                                if (item.range_min !== null) {
                                                    isInterval = isInterval && ((+item.range_min) <= (+item.check_value));
                                                }
                                                if (item.range_max !== null) {
                                                    isInterval = isInterval && ((+item.check_value) <= (+item.range_max));
                                                }

                                                if (item.check_value == '' || item.check_value == null) isInterval = false;

                                                if (isInterval) {
                                                    item.check_result = '0'; //ok 0
                                                    return 'check-point-ok';
                                                } else {
                                                    item.check_result = '1'; //ng 1
                                                    return 'check-point-notok';
                                                }
                                            }
                                            return '';
                                        }

                                    },
                                    type3Init: function (item) {
                                        if (!item) {
                                            return ''
                                        } else {
                                            if (!item.check_value) {
                                                item.check_result = '1';
                                                //  item.check_value = 2;
                                            }
                                        }

                                    },
                                    itemClick: function (item) {
                                        item.isClick = !item.isClick;
                                        if (item.check_value == '1') {
                                            item.check_result = '1'; //ng 1
                                            item.check_value = 2;
                                        } else {
                                            item.check_result = '0'; //ok 0
                                            item.check_value = 1;
                                        }
                                    },
                                    get_check_value: machine_parameter_info_get,
                                    back: function () {
                                        dialog.hide();
                                        if (options.back)
                                            options.back();
                                    },
                                    confirm: function () {
                                        var msg = '';
                                        var checklist_detail = [];
                                        dialog.machineCheckList_display.forEach(function (item) {
                                            if (item.check_type == '1' || item.check_type == '2') {
                                                if (item.do_flag) {
                                                    if (item.check_value == undefined || item.check_value === '') {
                                                        msg += $filter('translate')('B0210.no') + item.item_no
                                                            + $filter('translate')('B0210.msg.check_value_empty') + '<br>';
                                                    }
                                                }
                                            }
                                            //20210612 add by德義家興for#91011:排除check_value是null時check_value,check_result沒給值的問題
                                            if (item.check_type == '3' && item.check_value == null) {
                                                item.check_result = '1';
                                                item.check_value = 2;
                                            }

                                            // 20231206 modify by wenwei for M#152075: 【衡川科技】【正式区】设备点检文本类的填写数据显示点检不通过
                                            if (item.check_type == '4') item.check_result = ''

                                            // var detail = {
                                            //     item_no: item.item_no,
                                            //     check_value: item.check_value || '',
                                            //     check_result: item.check_result || ''
                                            // };
                                            checklist_detail.push(item);
                                        });
                                        if (msg == '') {

                                            var content = {
                                                eqpNo: dialog.machineItem.machine_no,
                                                plotNo: dialog.plotItem.plot_no,
                                                opNo: dialog.plotItem.op_no,
                                                productno: dialog.productno,
                                                qclistno: dialog.checklist_no,
                                                checklist_detail: checklist_detail,
                                                handle_user_no: dialog.handle_user_no,
                                                handle_time: dialog.handle_time[0] + " " + dialog.handle_time[1]
                                            }

                                            $MMWService.sendToServer({
                                                uri: 'ServicesCUS.Module_CUS.CUS_Product_QCList_Set_Process',
                                                content: content,
                                                success: function (data) {
                                                    $rootScope.showToast($filter('translate')('CUS001.showAlert'));
                                                    dialog.hide();
                                                    if (feedback)
                                                        feedback();
                                                }
                                            });

                                        } else {
                                            $rootScope.showAlert(msg);
                                        }
                                    }
                                }
                            }
                        );
                    })
                }

                // 查询产品编号 + 点检表信息
                var initProductQCList = function () {
                    $MMWService.sendToServer({
                        uri: 'ServicesCUS.Module_CUS.CUS_Product_QCList_Get_Process',
                        content: {
                            plotNo: plotItem.plot_no,
                            opNo: plotItem.op_no,
                        },
                        success: function (data) {
                            plotItem.productno = data.productno;

                            if (data.qcDetails)
                                data.qcDetails.forEach(function (item) {
                                    item.do_flag = true
                                });

                            openDialog(data.qcLists, data.qcLists[0].qclistno, data.qcLists[0].qclistname + "(" + data.qcLists[0].qclistno + ")", data.qcDetails, machineItem, areaItem, plotItem);
                        }
                    });
                }

                // 取得設備集成採集參數
                function machine_parameter_info_get(check_item) {
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_EQP.machine_parameter_info_get',
                        content: {
                            equipment_no: machine_no,
                            machine_parameters: [
                                { parameter_no: check_item.param_no }
                            ]
                        },
                        success: function (data) {
                            if (data.machine_checklist_get_checklist_detail.length > 0) {
                                check_item.check_value = data.machine_checklist_get_checklist_detail[0].value;
                            }
                        }
                    });
                }

                initProductQCList();
            };
        }]);
});
